import {
	startCheckStock,
	startMesLeveling,
	checkstockHDelete,
	mesCancelLeveling,
	erpLeveling,
	feedBackNewLVT,
	feedBackNewWPC,
	getNoDiskPageSet, closeCase,
} from '/@/api/platform/mes/wmsCheckstock';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useBizDict } from '/@/hooks/bizDict';
import { downBlobFile } from '/@/utils/other';

// const t = () =>{
//
//     return t
// }

interface ButtonItem {
	label: string;
	clickMethod: () => void;
	type: string;
	icon: string;
}

const { WarehouseDefinition } = useBizDict('WarehouseDefinition');
/**
 * 获取主界面按钮
 */
export const createMainBtnList = ({ t, createInventoryRef, multipleSelection, getDataList, uncountedBarcodeRef, k3ContrastRef, btnLoading }) => {
	/**
	 * 创建盘点单
	 * @param createInventoryRef
	 */

	const createCheckStock = () => {
		createInventoryRef.value.openDialog();
	};

	/**
	 * 启动盘点
	 * @param ids
	 * @param handleSuccess
	 */
	const startCheck = () => {
		const rows = multipleSelection.value;
		// 遍历检查盘点状态是不是 Create
		for (let i = 0; i < rows.length; i++) {
			const row = rows[i];
			if (row.status !== 'Create') {
				return useMessage().error('非`Create`状态,无法开始');
			}
		}
		const ids = multipleSelection.value.map((item) => item.id);
		if (ids?.length === 0) {
			return useMessage().warning('请选择盘点单');
		}
		useMessageBox()
			.confirm(`确认启动选中的 ${rows.length} 条盘点单?`)
			.then(async () => {
				btnLoading.startCheck = true;
				await startCheckStock(ids).then(
					(res) => {
						getDataList();
						useMessage().success('启动成功');
					},
					(error) => {
						useMessage().error(error?.msg || '启动失败');
					}
				);
				btnLoading.startCheck = false;
			});
	};
	/**
	 * mes库存调平
	 */
	const mesLeveling = () => {
		const rows = multipleSelection.value;

		// 2个仓库不允许盘点调平 SP,FG
		let b = rows.some((row) => {
			const warehouseCode = row.warehouseCode;
			if (['SP', 'FG'].includes(warehouseCode)) {
				useMessage().error(`仓库【${warehouseCode}】不允许【mes库存调平】`);
				return true;
			}
		});
		if (b) {
			return;
		}

		// 遍历检查盘点状态是不是 Audited
		for (let i = 0; i < rows.length; i++) {
			const row = rows[i];
			if (row.status !== 'Audited') {
				return useMessage().error('非`Audited`状态,无法【mes库存调平】');
			}
		}
		const ids = multipleSelection.value.map((item) => item.id);
		if (ids?.length === 0) {
			return useMessage().warning('请选择盘点单');
		}
		useMessageBox()
			.confirm(`确认【mes库存调平】选中的 ${rows.length} 条盘点单?`)
			.then(async () => {
				btnLoading.mesLeveling = true;
				await startMesLeveling(ids).then(
					(res) => {
						if (res?.code == 0) {
							getDataList();
							useMessage().success('【mes库存调平】成功');
						} else {
							useMessage().error(res?.msg || '【mes库存调平】失败');
						}
					},
					(error) => {
						useMessage().error(error?.msg || '【mes库存调平】失败');
					}
				);
				btnLoading.mesLeveling = false;
			});
	};
	/**
	 * 撤销库存调平
	 */
	const cancelMesLevelling = () => {
		const rows = multipleSelection.value;
		// 遍历检查盘点状态是不是 LevelEnd
		for (let i = 0; i < rows.length; i++) {
			const row = rows[i];
			if (row.status !== 'LevelEnd') {
				return useMessage().error('非`LevelEnd`状态,无法【撤销库存调平】');
			}
		}
		const ids = multipleSelection.value.map((item) => item.id);
		if (ids?.length === 0) {
			return useMessage().warning('请选择盘点单');
		}
		useMessageBox()
			.confirm(`确认【撤销库存调平】选中的 ${rows.length} 条盘点单?`)
			.then(async () => {
				btnLoading.cancelLeveling = true;
				await mesCancelLeveling(ids).then(
					(res) => {
						if (res?.code == 0) {
							getDataList();
							useMessage().success('【撤销库存调平】成功');
						} else {
							useMessage().error(res?.msg || '【撤销库存调平】失败');
						}
					},
					(error) => {
						useMessage().error(error?.msg || '【撤销库存调平】失败');
					}
				);
				btnLoading.cancelLeveling = false;
			});
	};
	/**
	 * 回写erp
	 */
	const writeBackErp = () => {
		const rows = multipleSelection.value;
		// 2个仓库不允许回写erp SP,FG RM
		let b = rows.some((row) => {
			const warehouseCode = row.warehouseCode;
			if (['SP', 'FG', 'RM'].includes(warehouseCode)) {
				useMessage().error(`仓库【${warehouseCode}】不允许【回写erp】`);
				return true;
			}
		});
		if (b) {
			return;
		}
		// 遍历检查盘点状态是不是 LevelEnd
		for (let i = 0; i < rows.length; i++) {
			const row = rows[i];
			if (row.status !== 'LevelEnd') {
				return useMessage().error('非`LevelEnd`状态,无法【回写erp】');
			}
		}

		const ids = multipleSelection.value.map((item) => item.id);
		if (ids?.length === 0) {
			return useMessage().warning('请选择盘点单');
		}
		useMessageBox()
			.confirm(`确认【回写erp】选中的 ${rows.length} 条盘点单?`)
			.then(async () => {
				btnLoading.writeBackErp = true;
				await erpLeveling(ids).then(
					(res) => {
						if (res?.code == 0) {
							getDataList();
							useMessage().success('【回写erp】成功');
						} else {
							useMessage().error(res?.msg || '【回写erp】失败');
						}
					},
					(error) => {
						useMessage().error(error?.msg || '【回写erp】失败');
					}
				);
				btnLoading.writeBackErp = false;
			});
	};
	/**
	 * 结案
	 */
	const closing = () => {
		const rows = multipleSelection.value;
		// 遍历检查盘点状态是不是 Audited
		const ids = multipleSelection.value.map((item) => item.id);
		if (ids?.length === 0) {
			return useMessage().warning('请选择盘点单');
		}
		useMessageBox()
			.confirm(`确认【结案】选中的 ${rows.length} 条盘点单?`)
			.then(async () => {
				btnLoading.closing = true;
				await closeCase(ids).then(
					(res) => {
						if (res?.code == 0) {
							getDataList();
							useMessage().success('【结案】成功');
						} else {
							useMessage().error(res?.msg || '【结案】失败');
						}
					},
					(error) => {
						useMessage().error(error?.msg || '【结案】失败');
					}
				);
				btnLoading.closing = false;
			});
	};

	/**
	 * 回料报工
	 */
	const feedback = async () => {
		let f = true;
		// await feedBackNewLVT().then({}, (error) => {
		// 	f = false;
		// 	useMessage().error(error.msg);
		// });
		await feedBackNewWPC().then({}, (error) => {
			f = false;
			useMessage().error(error.msg);
		});
		if (f) {
			useMessage().success('回料报功操作完成');
		}
	};
	/**
	 * 未盘条码
	 */
	const noDisk = () => {
		const billCodes = multipleSelection.value.map((item) => item.billCode);
		if (billCodes?.length === 0) {
			return useMessage().warning('请选择盘点单');
		} else if (billCodes?.length > 1) {
			return useMessage().warning('只可选择一个盘点单');
		}

		uncountedBarcodeRef.value.openDialog(billCodes[0]);
	};
	/**
	 * 实盘K3对比
	 */
	const contrastK3 = () => {
		const billCodes = multipleSelection.value.map((item) => item.billCode);
		if (billCodes?.length === 0) {
			return useMessage().warning('请选择盘点单');
		} else if (billCodes?.length > 1) {
			return useMessage().warning('只可选择一个盘点单');
		}
		k3ContrastRef.value.openDialog(multipleSelection.value[0])
	};
	/**
	 * 删除
	 */
	const deleteBill = () => {
		const ids = multipleSelection.value.map((item) => item.id);
		if (ids?.length === 0) {
			return useMessage().warning('请选择要删除的项');
		}
		useMessageBox()
			.confirm('此操作将永久删除')
			.then(async () => {
				checkstockHDelete(ids).then(
					(res) => {
						getDataList();
						useMessage().success('删除成功');
					},
					(error) => {
						useMessage().error(error?.msg || '删除失败');
					}
				);
			});
	};
	return reactive<ButtonItem[]>([
		{
			// 创建盘点单
			label: t('checkStock.create'),
			clickMethod: createCheckStock,
			type: 'success',
			plain: true,
			icon: 'plus',
		},
		{
			// 启动盘点
			label: t('checkStock.start'),
			clickMethod: startCheck,
			type: 'success',
			key: 'startCheck',
			icon: 'check',
		},
		{
			label: t('checkStock.mesLeveling'),
			type: 'primary',
			icon: 'SuccessFilled',
			key: 'mesLeveling',
			clickMethod: mesLeveling,
		},
		{
			label: t('checkStock.cancelLeveling'),
			type: 'warning',
			icon: 'CircleCloseFilled',
			key: 'cancelLeveling',
			clickMethod: cancelMesLevelling,
		},
		{
			label: t('checkStock.writeBackErp'),
			type: 'danger',
			icon: 'Back',
			key: 'writeBackErp',
			clickMethod: writeBackErp,
		},
		{
			label: t('checkStock.closing'),
			type: 'info',
			icon: 'SwitchButton',
			key: 'closing',
			clickMethod: closing,
		},
		{
			label: t('checkStock.feedback'),
			type: 'primary',
			icon: 'Refresh',
			plain: true,
			clickMethod: feedback,
		},
		{
			label: t('checkStock.NoDisk'),
			type: 'primary',
			icon: 'Refresh',
			plain: true,
			clickMethod: noDisk,
		},
		{
			label: t('checkStock.ContrastK3'),
			type: 'primary',
			icon: 'Connection',
			plain: true,
			clickMethod: contrastK3,
		},
		{
			label: t('checkStock.delete'),
			type: 'danger',
			icon: 'Delete',
			key: 'deleteBill',
			clickMethod: deleteBill,
		},
	]);
};

export const mainDgFunctions = (t, state, multipleSelection) => {
	/**
	 * 导出盘点清册
	 */
	const ExportList = () => {
		const billCodes = multipleSelection.value.map((item) => item.billCode);
		if (billCodes?.length === 0) {
			return useMessage().warning('请选择要导出的盘点单');
		}
		const searchForm = {
			billCodes: billCodes.join(','),
		};
		downBlobFile('/eletile-mes/wmsCheckstockH/exportExcelInventoryDetails', searchForm, '盘点清册' + new Date().getTime() + '.xlsx');
	};
	/**
	 * 导出调平明细
	 * @constructor
	 */
	const ExportLevelingDetail = () => {
		const billCodes = multipleSelection.value.map((item) => item.billCode);
		if (billCodes?.length === 0) {
			return useMessage().warning('请选择要导出的盘点单');
		}
		const searchForm = {
			billCodes: billCodes.join(','),
		};
		downBlobFile('/eletile-mes/wmsCheckstockH/exportExcelLevelingDetails', searchForm, '调平明细' + new Date().getTime() + '.xlsx');
	};
	/**
	 * 导出库存差异
	 * @constructor
	 */
	const ExportInventoryVariance = () => {
		const billCodes = multipleSelection.value.map((item) => item.billCode);
		if (billCodes?.length === 0) {
			return useMessage().warning('请选择要导出的盘点单');
		}
		const searchForm = {
			billCodes: billCodes.join(','),
		};
		downBlobFile('/eletile-mes/wmsCheckstockH/exportInventoryVariance', searchForm, '库存差异' + new Date().getTime() + '.xlsx');
	};

	/**
	 * 导出
	 * @param command
	 */
	const exportCommand = (command) => {
		switch (command) {
			case '1':
				ExportList();
				break;
			case '2':
				ExportLevelingDetail();
				break;
			default:
				ExportInventoryVariance();
		}
	};
	/**
	 * 创建盘点: 从数据字典中获取仓库列表信息
	 */
	const getWarehouseDataList = () => {
		// 遍历WarehouseDefinition ,组成一个新的list
		const myMap = new Map();
		WarehouseDefinition.value.forEach((item) => {
			// text相同的数据需要合并
			if (!myMap.has(item.text)) {
				myMap.set(item.text, item.value);
			} else {
				myMap.set(item.text, `${myMap.get(item.text)},${item.value}`);
			}
		});
		// 遍历myMap，组成一个新的list
		state.dataList.length = 0;
		myMap.forEach((value, key) => {
			state.dataList.push({ k3Code: key, code: value });
		});
	};

	const getUncountedBarcodeList = (billCode) => {};

	return { exportCommand, getWarehouseDataList, getUncountedBarcodeList };
};

const statusColorMap = new Map([
	['Create', { type: 'primary', effect: 'plain' }],
	['Checking', { type: 'success', effect: 'plain' }],
	['Audited', { type: 'warning', effect: 'plain' }],
	['Leveling', { type: 'danger', effect: 'plain' }],
	['LevelEnd', { type: 'warning', effect: 'light' }],
	['ERPLeveling', { type: 'danger', effect: 'light' }],
	['Closed', { type: 'info', effect: 'plain' }],
]);
// 通过状态获取tag标签的属性
export const getTagAttrByStatus = (status) => {
	return statusColorMap.get(status);
};
// 根据value获取数据字典中的值
export const getCheckStatusItemText = (value: string) => {
	// 从数据字典获取盘点的状态
	const { CheckStatus } = useBizDict('CheckStatus');
	if (!CheckStatus.value) {
		return value;
	}
	return CheckStatus.value.find((item: any) => item.value === value)?.text || value;
};
